package com.substation.ui.activity;

import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bean.LoginInfo;
import com.greenentity.Logger;
import com.greenentity.Substation;
import com.jessewu.library.SuperAdapter;
import com.jessewu.library.view.ViewHolder;
import com.net.SubstationNet;
import com.substation.R;
import com.substation.greendao.LoggerDao;
import com.substation.greendao.SubstationDao;
import com.substation.ui.weight.MySpinnerOnItemSelectedListener;
import com.substation.utils.DateUtils;
import com.substation.utils.GreenDaoManager;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;

public class LoggerActivity extends BaseListActivity {

    List<Substation> substations;
    String guid = "全部", my = "我的";
    Date date;
    @BindView(R.id.spinner1)
    Spinner spinner1;
    @BindView(R.id.spinner2)
    Spinner spinner2;
    @BindView(R.id.spinner3)
    Spinner spinner3;

    List<Logger> datas = new ArrayList<>();
    SuperAdapter<Logger> adapter;
    Calendar c = Calendar.getInstance();
    Logger lg;//上传的日志

    @Override
    protected int getMyListLayoutId() {
        return R.layout.activity_logger;
    }

    @Override
    protected void initView() {
        super.initView();
        refresh.setRefreshing(false);
        refresh.setEnabled(false);
        adapter.setData(datas);
        adapter.setEmptyDataView(R.layout.view_empty);
        c.setTime(new Date());
        c.add(Calendar.MONTH, -1);
        date = c.getTime();
        substations = GreenDaoManager.getInstance().getmDaoSession().getSubstationDao().loadAll();
        List<String> sp1 = new ArrayList<>();
        sp1.add("全部");
        for (Substation substation : substations) {
            sp1.add(substation.getNames());
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_txt, sp1);
        adapter.setDropDownViewResource(R.layout.spinner_txt);
        spinner1.setAdapter(adapter);
        spinner1.setOnItemSelectedListener(new MySpinnerOnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                super.onItemSelected(adapterView, view, i, l);
                if (i == 0) guid = "全部";
                else guid = substations.get(i - 1).getGuid();
                getData();
            }
        });
        spinner2.setOnItemSelectedListener(new MySpinnerOnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                super.onItemSelected(adapterView, view, i, l);
                c.setTime(new Date());
                switch (i) {
                    case 0:
                        c.add(Calendar.MONTH, -1);
                        break;
                    case 1:
                        c.add(Calendar.MONTH, -3);
                        break;
                    case 2:
                        c.add(Calendar.MONTH, -6);
                        break;
                    case 3:
                        c.add(Calendar.YEAR, -1);
                        break;
                }
                date = c.getTime();
                getData();
            }
        });
        spinner3.setOnItemSelectedListener(new MySpinnerOnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                super.onItemSelected(adapterView, view, i, l);
                if (i == 0) my = "我的";
                else my = "全部";
                getData();
            }
        });
    }

    @Override
    protected void initData() {
        getData();
    }

    void getData() {
        datas.clear();
        QueryBuilder<Logger> loggerQueryBuilder = GreenDaoManager.getInstance().getmDaoSession().getLoggerDao().queryBuilder();
        if (!guid.equals("全部")) {
            loggerQueryBuilder.where(LoggerDao.Properties.SubsGuids.eq(guid));
        }
        if (my.equals("我的")) {
            loggerQueryBuilder.where(LoggerDao.Properties.UserId.eq(LoginInfo.getInfo(context).getAccountProfileDetails().getObjectId()));
        }
        loggerQueryBuilder.where(LoggerDao.Properties.AddTime.ge(date)).orderDesc(LoggerDao.Properties.Status).orderDesc(LoggerDao.Properties.AddTime);
        datas.addAll(loggerQueryBuilder.list());
        adapter.notifyDataSetChanged();
    }

    @Override
    public SuperAdapter getAdapter() {
        return adapter = new SuperAdapter<Logger>(R.layout.content_logger) {
            @Override
            public void bindView(ViewHolder viewHolder, final Logger logger, int i) {
                ((TextView) viewHolder.getView(R.id.name)).setText(logger.getUserName());
                Substation unique = GreenDaoManager.getInstance().getmDaoSession().getSubstationDao().queryBuilder()
                        .where(SubstationDao.Properties.Guid.eq(logger.getSubsGuids())).unique();
                ((TextView) viewHolder.getView(R.id.sub)).setText(unique.getNames());
                ((TextView) viewHolder.getView(R.id.type)).setText(logger.getLogsNaturevalue());
                ((TextView) viewHolder.getView(R.id.content)).setText(logger.getLogsContent());
                ((TextView) viewHolder.getView(R.id.time)).setText(DateUtils.DateToString(logger.getAddTime()));
                if (logger.getStatus().equals("新增")) {
                    viewHolder.getView(R.id.line1).setVisibility(View.VISIBLE);
                    viewHolder.getView(R.id.button_layout).setVisibility(View.VISIBLE);
                } else {
                    viewHolder.getView(R.id.line1).setVisibility(View.GONE);
                    viewHolder.getView(R.id.button_layout).setVisibility(View.GONE);
                }
                viewHolder.getView(R.id.upload).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        lg = logger;
                        SubstationNet.uploadGsubslog(context, logger, LoggerActivity.this);
                    }
                });
                viewHolder.getView(R.id.edit).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(context, LoggerAddActivity.class);
                        intent.putExtra("logger", logger);
                        startActivity(intent);
                    }
                });
                viewHolder.getView(R.id.delete).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        datas.remove(logger);
                        adapter.notifyDataSetChanged();
                        GreenDaoManager.getInstance().getmDaoSession().getLoggerDao().delete(logger);
                    }
                });
            }
        };
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_logger, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.refer:
                SubstationNet.downGsubslog(context, this);
                return true;
            case R.id.add:
                startActivity(new Intent(context, LoggerAddActivity.class));
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void success(int i, String obj) {
        switch (i) {
            case 1:
                List<Logger> loggers = JSON.parseArray(obj, Logger.class);
                GreenDaoManager.getInstance().getmDaoSession().getLoggerDao().queryBuilder()
                        .where(LoggerDao.Properties.Status.notEq("新增")).buildDelete().executeDeleteWithoutDetachingEntities();
                for (Logger logger : loggers) {
                    logger.setStatus("历史");
                }
                GreenDaoManager.getInstance().getmDaoSession().getLoggerDao().insertOrReplaceInTx(loggers);
                getData();
                break;
            case 2:
                lg.setStatus("历史");
                GreenDaoManager.getInstance().getmDaoSession().getLoggerDao().update(lg);
                getData();
                break;
        }
    }
}
